package com.audaque.jadmin.system.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.audaque.jadmin.common.action.BaseAction;
import com.audaque.jadmin.common.model.MessageModel;
import com.audaque.jadmin.system.model.vo.LoginVO;
import com.audaque.jadmin.system.shiro.CaptchaException;
import com.audaque.jadmin.system.shiro.UsernamePasswordCaptchaToken;

/**
 * @Description :
 * @FileName: IndexAction.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年10月15日 上午9:39:26
 * @Version:V1.00
 */
@Controller
public class LoginAction extends BaseAction {

	protected final static String PATH = "";

	@Override
	protected String getJspPathPrefix() {
		return PATH;
	}

	/**
	 * 默认页面,bug:执行3便???
	 */
	// @RequestMapping(value = "login", method = RequestMethod.GET)
	// public String toLogin() {
	// // 第一种：检查session中用户是否已登录 如果已经登录 则直接跳转后台
	// // String userName = CookieUtil.getCookie(request,
	// // Constants.CURRENT_USER_NAME);
	// // 第二种：检查session中用户是否已登录 如果已经登录 则直接跳转后台
	// Subject subject = SecurityUtils.getSubject();
	// if (subject.isAuthenticated() || subject.isRemembered()) {
	// // 跳转后台 home
	// return "redirect:/home";
	// }
	// // html登录页
	// return "beetl/login";
	// }

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String toIndex() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated() || subject.isRemembered()) {
			return "redirect:/index";
		}
		return "beetl/login";
	}

	/**
	 * 登录失败,第一种登录方式
	 * 
	 * @param request
	 * @return
	 */
	// @RequestMapping(value = "login", method = RequestMethod.POST)
	// public MessageModel fail(HttpServletRequest request) {
	// MessageModel model = new MessageModel(false);
	// String error = (String)
	// request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
	//
	// LOG.debug("login fail msg : " + error);
	//
	// if ("com.audaque.jadmin.system.shrio.CaptchaException".equals(error)) {
	// model.setMsg("验证码错误，请重试");
	// }
	// if ("org.apache.shiro.authc.UnknownAccountException".equals(error)) {
	// model.setMsg("用户名不存在，请重试");
	// }
	// if ("org.apache.shiro.authc.IncorrectCredentialsException".equals(error))
	// {
	// model.setMsg("帐号或密码错误，请重试");
	// }
	// return model;
	// }

	// 验证登录
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public MessageModel login(@Valid @ModelAttribute final LoginVO loginVO, BindingResult bindingResult,
			HttpSession session, HttpServletRequest request) {

		List<FieldError> fieldErrors = bindingResult.getFieldErrors();
		MessageModel messageModel = new MessageModel(true);

		if (fieldErrors != null && !fieldErrors.isEmpty()) {
			String defaultMessage = fieldErrors.get(0).getDefaultMessage();
			messageModel.setSuccess(false);
			messageModel.setMsg(defaultMessage);
			return messageModel;
		}

		// 验证登录
		AuthenticationToken token = new UsernamePasswordCaptchaToken(loginVO.getUsername(),
				loginVO.getPassword().toCharArray(), loginVO.getCaptcha());
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			e.printStackTrace();
			messageModel.setSuccess(false);
			if (e instanceof CaptchaException) {
				messageModel.setMsg("验证码错误，请重试");
			}
			if (e instanceof UnknownAccountException) {
				messageModel.setMsg("用户名不存在，请重试");
			}
			if (e instanceof IncorrectCredentialsException) {
				messageModel.setMsg("帐号或密码错误，请重试");
			}
			return messageModel;
		}
		return messageModel;
	}

	// 验证码图片
//	@RequestMapping("/authCode")
//	public void authCode(HttpServletResponse response, HttpSession session) throws IOException {
//		// Set standard HTTP/1.1 no-cache headers.
//		response.setHeader("Cache-Control", "no-store, no-cache");
//		// return a jpeg
//		response.setContentType("image/jpeg");
//		// create the text for the image
//		String text = captchaProducer.createText();
//		// create the image with the text
//		BufferedImage image = captchaProducer.createImage(text);
//		ServletOutputStream outputStream = response.getOutputStream();
//		// write the data out
//		ImageIO.write(image, "JPG", outputStream);
//		// store the text in the session
//		session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
//		outputStream.flush();
//		outputStream.close();
//	}

	/**
	 * 登出
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request, HttpServletResponse response) {
		// String userName = CookieUtil.getCookie(request,
		// Constants.CURRENT_USER_NAME);
		// String userType = CookieUtil.getCookie(request,
		// Constants.CURRENT_USER_TYPE);
		// LOG.info("user[" + userName + "," + userType + "] loginout");
		// this.clearCookie(request, response, userName);
		SecurityUtils.getSubject().logout();
		return "beetl/login";
	}

}
